Components.utils.import("resource://lucidity/lucidapi.jsm");
Components.utils.import("resource://gre/modules/JSON.jsm");

var lucidctx = new (lucidapi.CryptoOperator.extend(function(classref) { return {
    initialize: function()
    {
        classref.superClass.initialize.call(this,window);
    },
    handleInplaceResult: function( resultobj )
    {
        var stuff = resultobj.m_result;
        var sigdata = resultobj.m_siginfo;
        if (stuff)
        {
            setSelectedText(stuff);
        }

        updateSignatureStatus(sigdata);
        return true;
    },
    getInvocationTarget: function()
    {
        var text = document.getElementById('text')
        var value = text.value;
        value = value.substring(text.selectionStart, text.selectionEnd)
        if (value == "")
            value = text.value;
        return value;
    },
    openFileInEditor: function()
    {
        try
        {
            var data = lucidapi.loadThingWithPicker(window);
            if (data)
                document.getElementById('text').value = data;
        }
        catch (e)
        {
            lucidapi.promptError(e);
        }
    },

    invokeSave: function()
    {
        var data = document.getElementById('text').value;
        lucidapi.saveThingWithPicker(window, data);
    }

}}))

function setSelectedText( text )
{
    var txtbox = document.getElementById('text');
    var startPos = txtbox.selectionStart;
    var endPos = txtbox.selectionEnd;
    var chaine = txtbox.value;
    if (startPos != endPos)
    {
        txtbox.value = chaine.substring(0, startPos) + text + chaine.substring(endPos, chaine.length);
    }
    else
    {
        txtbox.value = text;
    }
    lucid_goUpdateCommands();
}


function updateSignatureStatus(sigdata)
{
    var sigel = document.getElementById('sigresult-statuspanel');
    if (sigdata)
    {
        sigel.label = lucidapi.formatSignatureResultMessage(sigdata);
    }
    else
    {
        sigel.label = 'none detected';
    }
}

this.onLoad = function(win)
{
    if (win.arguments == undefined)
        return;

    var optopts = JSON.fromString(win.arguments[0]);

    var maintext = document.getElementById('text');
    maintext.value = optopts.text;
    updateSignatureStatus(optopts.siginfo);
    lucid_goUpdateCommands();
}

